import { SampledInfo, SampledResult, SampleMethod, SampleParameterValues, SampleSortField, SampleStepInfo, WhereSqlParams } from "@/pages/auditSampling/typing";
import { getSampleOverallWhereSQL } from "../../samplingProjectOverallService";
import { getIniSampledResult, getTextFieldsValues, getToBeTestWhereSql } from "../NonStatSampleService";
import { getRealTableName } from "../../service";
import getApiData from "@/services/cpasRequest";
import { msgError } from "@/utils/msg";
import { consts } from "@/pages/auditSampling/consts";

/**
 * 系统抽样,抽取数字
 * @param total B.待抽样的测试总体(扣除特定项目后)	
 * @param interval 间隔 2,抽第0,3,6,9,12,...的index序号,样本应该是1,4,7,....
 * @param isAscending 自上而下的顺序/自下而上的顺序
 * @returns 
 */
export function getSystemSampleNos(total: number, interval: number, isAscending: boolean = true): number[] {
  const result: number[] = [];
  // 
  if (isAscending) {
    for (let i = 0; i < total; i += (interval + 1)) {
      result.push(i + 1);
    }
  } else {
    // for (let i = total - (total % (interval+1)); i >= 1; i -= 0) {
    for (let i = total - 1; i >= 0; i -= (interval + 1)) {
      result.push(i + 1);
    }
  }
  console.log('getSystemSampleNos', result)
  return result;
}
/**
 * 随机或系统抽样
 * @param sampleStepInfo 
 * @param sampleParameterValues 
 * @param sampleNos 
 * @param sortFields 
 * @returns 
 */
export async function getRandomOrSystemSampleList(
  sampleStepInfo: SampleStepInfo, sampleParameterValues: SampleParameterValues,
  sampleNos: number[], sortFields?: string[]): Promise<SampledResult> {
  //const layerSampleParams = sampleParameterValues.layerSampleParams || {}
  const curSampleTable = sampleStepInfo.projectOverallProps?.curSampleTable;
  const sampleTextFieldsArray = curSampleTable?.sampleTextFieldsArray || [];
  const sampleNumFieldsArray = curSampleTable?.sampleNumFieldsArray || [];

  const sampleWhereSQL = getSampleOverallWhereSQL(sampleStepInfo.projectOverallProps?.curWhereSqlParams as WhereSqlParams)
  const toBeTestWhereSql = getToBeTestWhereSql(sampleParameterValues);


  const tableInfoList = sampleNumFieldsArray.map(fieldName => {
    const tableName = getRealTableName(sampleStepInfo.projectOverallProps?.curSampleTable?.tableName || ''
      , { data_id: sampleStepInfo.projectOverallProps?.curDataId || '' });
    const whereSql = ` ${sampleWhereSQL} ${toBeTestWhereSql}  `
    return { tableName, whereSql, amountField: fieldName }
  })

  sortFields = sortFields || sampleStepInfo.projectOverallProps?.curSampleTable?.sortFieldsArray || [];
  console.log('getRandomOrSystemSampleList.sampleNos', sampleNos)
  //增加排序字段到fields时,要删除排序asc和desc,且要把sampleTextFieldsArray中存在的排除
  let newSortFields = sortFields.map(fieldName =>
    fieldName.replace(' asc', '').replace(' ASC', '')
      .replace(' desc', '').replace(' DESC', '')
      .replace('[', '').replace(']', '')
      .replace('[', '').replace(']', '')
      .replace('abs(ISNULL(', '')
      .replace(',0))', '')//abs(ISNULL([JFJE],0)) asc"
      .trim()
  ).filter(sortFieldName => !sampleTextFieldsArray.some(textFieldName =>
    textFieldName == sortFieldName || sortFieldName.includes(`(${textFieldName},`)
  ))

  //JFJE_DFJE_Field要替换
  sortFields.forEach((item, index) => {
    if (item.includes(consts.JFJE_DFJE_ABS)) {
      sortFields[index] = item.replace(consts.JFJE_DFJE_ABS, consts.JFJE_DFJE_Field)
    }
  });

  const fields: string = new Array(...new Set(sampleTextFieldsArray
    .concat(newSortFields/* .filter(item => item !== consts.JFJE_DFJE_Field_Not_FKH) */))) //借方或贷方金额 不加到fields中
    .map(fieldName => fieldName.includes('[') ? fieldName : `[${fieldName}]`)
    .map(item => item = item == consts.JFJE_DFJE_ABS ? consts.JFJE_DFJE_Field_SEP : item)
    .join(',');


  const isVoucher = sampleStepInfo.projectOverallProps?.curSampleTable?.isVoucher;

  const retData = await getApiData('sample.getRandomOrSystemSampleList', {
    dbname: sampleStepInfo.projectOverallProps?.curWhereSqlParams?.dbname,
    sortFields: sortFields.join(','),//排序字段
    fields: fields,//需要返回的字段
    tableInfoList: tableInfoList,
    sampleNos,
    isAddAmountFieldCondition: isVoucher && tableInfoList.length > 0,//加这个  CPAS6ZT-3392
    otherFields: sortFields.some(item => item.startsWith(consts.JFJE_DFJE_Field)) ? ' ,JFJE,DFJE ' : '',//其他字段
  })
  if (!retData.ok) {
    msgError(retData.data);
    return getIniSampledResult()
  } else {
    const sampledList: SampledInfo[] = retData.data;
    const sampledSize = sampledList.length;
    let sampledAmountSum = 0;
    sampledList.forEach(item => sampledAmountSum += (item.amountFieldValue || 0));
    const sampleTextFieldValues = sampledList.map(item => getTextFieldsValues(item, sampleTextFieldsArray))
    return { sampledList, sampledSize, sampledAmountSum, sampleTextFieldValues };
  }

}

/**
 * pps抽样
 * @param sampleStepInfo 
 * @param sampleParameterValues 
 * @param sampleNos 
 * @param sortFields 
 * @returns 
 */
export async function getPPSSampleList(sampleStepInfo: SampleStepInfo,
  sampleParameterValues: SampleParameterValues, seed: string): Promise<SampledResult> {
  //const layerSampleParams = sampleParameterValues.layerSampleParams || {}
  const curSampleTable = sampleStepInfo.projectOverallProps?.curSampleTable;
  const sampleTextFieldsArray = curSampleTable?.sampleTextFieldsArray || [];
  const sampleNumFieldsArray = curSampleTable?.sampleNumFieldsArray || [];

  const sampleWhereSQL = getSampleOverallWhereSQL(sampleStepInfo.projectOverallProps?.curWhereSqlParams as WhereSqlParams)
  const toBeTestWhereSql = getToBeTestWhereSql(sampleParameterValues);


  let sortFields = sampleStepInfo.projectOverallProps?.curSampleTable?.sortFieldsArray || [consts.defaultNullSort];

  const isVoucher = sampleStepInfo.projectOverallProps?.curSampleTable?.isVoucher;
  let numFields: string = `ABS(${sampleNumFieldsArray[0]})`;
  let otherFields = ''
  if (isVoucher) {
    //如果是凭证表,且包含借方和贷方金额
    if (sampleNumFieldsArray.filter(item => consts.JFJE_DFJE_Array.includes(item)).length == consts.JFJE_DFJE_Array.length) {
      numFields = consts.JFJE_DFJE_Array.map(item => `ABS(ISNULl(${item},0))`).join('+')
      otherFields = ',' + consts.JFJE_DFJE_Array.map(item => `ISNULl(${item},0) as ${item}`).join(',')
    }
  }

  const retData = await getApiData('sample.getPPSSampleList', {
    dbname: sampleStepInfo.projectOverallProps?.curWhereSqlParams?.dbname,
    tableName: getRealTableName(sampleStepInfo.projectOverallProps?.curSampleTable?.tableName || ''
      , { data_id: sampleStepInfo.projectOverallProps?.curDataId || '' }),
    sortFields: sortFields.join(','),//排序字段
    fields: sampleTextFieldsArray.join(','),//需要返回的字段
    numFields: numFields,
    whereSql: ` ${sampleWhereSQL} ${toBeTestWhereSql}  `,
    seed: seed,
    otherFields: otherFields,
    extractNumber: sampleParameterValues.ppsSampleParams?.extractNumber,
  })
  if (!retData.ok) {
    msgError(retData.data);
    return getIniSampledResult()
  } else {
    const sampledList: SampledInfo[] = retData.data;
    const sampledSize = sampledList.length;
    let sampledAmountSum = 0; debugger
    sampledList.forEach(item => sampledAmountSum += (item.amountFieldValue || 0));
    const sampleTextFieldValues = sampledList.map(item => getTextFieldsValues(item, sampleTextFieldsArray))
    return { sampledList, sampledSize, sampledAmountSum, sampleTextFieldValues };
  }

}

/**
 * 排序字段
 * @param sampleSortFields 
 * @returns 
 */
export function getSystemSortFields(sampleSortFields: SampleSortField[]) {
  return sampleSortFields.filter(field => field.fieldName).map(field => {
    let fieldName = field.fieldName;
    if (field.isAbs) fieldName = `abs(ISNULL([${fieldName}],0))`;
    if (!fieldName?.includes('[')) {
      fieldName = `[${fieldName}]`
    }
    return `${fieldName} ${field.sortType}`
  })
  // sampleParameterValues.systemSampleParams?.sampleSortFields
}